<template>
  <div class="container">
    <div v-if="!mchInfo">
      <el-steps :active="active" finish-status="success" :space="300" align-center style="justify-content: center;" >
        <el-step title="注册/填写商户"></el-step>
        <el-step title="门店创建"></el-step>
      </el-steps>

    <!-- 注册商户号 76248  -->
    <!-- {{mchInfo.length}} -->
      <div v-if="active == 0" style="width: 500px;margin:12px auto;">
        <div v-if="mchCate">
          <el-form ref="form" :model="mchForm" label-width="100px" >
            <el-form-item label="手机号">
              <el-input v-model="mchForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="所在城市">
              <el-select v-model="mchForm.city" clearable placeholder="请选择城市">
                <el-option v-for="(item,index) in cityCode" :key="index" :label="item.cityName" :value="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="门店全称">
              <el-input v-model="mchForm.enterprise_name"></el-input>
             <!--  <el-col :span="11">
                <el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-time-picker type="fixed-time" placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>
              </el-col> -->
            </el-form-item>
            <el-form-item label="门店地址">
              <el-input v-model="mchForm.enterprise_address"></el-input>
            </el-form-item>
            <el-form-item label="联系人姓名">
              <el-input v-model="mchForm.contact_name"></el-input>
            </el-form-item>
            <el-form-item label="联系人电话">
              <el-input v-model="mchForm.contact_phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱地址">
              <el-input type="email" v-model="mchForm.email"></el-input>
            </el-form-item>
            <el-form-item>
              <!-- <el-button type="primary" @click="onSubmit">立即创建</el-button>
              <el-button>取消</el-button> -->
              <p style="color: #ff00009e;font-size: 12px;">* 生成的初始化密码会以短信形式发送给注册手机号,请留意短信接收</p>
            </el-form-item>
          </el-form>

          <el-button type="primary" plain @click="hasMch()">我已有达达账号</el-button>
        </div>


        <div v-if="!mchCate">
          <el-form ref="form" :model="form" label-width="100px">
              <el-form-item label="商户编号(source_id):">
                <el-input v-model="form.source_id"></el-input>
              </el-form-item>
              <el-form-item label="所在城市">
              <el-select v-model="form.city_code" clearable placeholder="请选择城市">
                <el-option v-for="(item,index) in cityCode" :key="index" :label="item.cityName" :value="item.cityCode"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-button type="primary" plain @click="noMch()">我没有达达账号</el-button>
        </div>
         <el-button v-if="active < 1" style="margin:12px 50%;" @click="next" :disabled= "mchForm.mobile != '' || form.source_id !='' ? false:true ">下一步</el-button>

        
      </div>
<!-- 添加门店 -->
      <div v-if="active == 1" style="width: 500px;margin:12px auto;">
         <el-form ref="form" :model="shopForm" label-width="100px" >
          <el-form-item label="门店名称">
            <el-input v-model="shopForm.station_name"></el-input>
          </el-form-item>
          <el-form-item label="门店编码">
            <el-input v-model="shopForm.origin_shop_id"></el-input>
          </el-form-item>
  <!--         <el-form-item label="业务类型">
            <el-select v-model="shopForm.business_type" clearable placeholder="请选择类型">
              <el-option v-for="(item,index) in business" :label="item.type" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="所在城市">
              <el-select v-model="shopForm.city_name" clearable placeholder="请选择城市">
                <el-option v-for="(item,index) in cityCode" :key="index" :label="item.cityName" :value="item.cityName"></el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="区域名称">
            <el-input v-model="shopForm.area_name"></el-input>
          </el-form-item>
          <el-form-item label="联系人姓名">
            <el-input v-model="shopForm.contact_name"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话">
            <el-input v-model="shopForm.phone"></el-input>
          </el-form-item>

          <el-form-item label="门店地址选取">
           <div class="amap-page-container">
              <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
              <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo"  :plugin="plugin"  :events="events">
                  <el-amap-marker vid="amapDemo" :position="center" icon="https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" ></el-amap-marker>
                  <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker" :events="clickMarker"></el-amap-marker>    
                  <!-- :icon=" marker == center ? 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png':'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png'"  -->
                  
              </el-amap>
              <div class="toolbar">
               <!--  position: [{{ admininfo.shopLon }}, {{ admininfo.shopLat }}] address: {{ admininfo.shopAddress }} -->
                <!-- position: [{{ lng }}, {{ lat }}] address: {{ address }} -->
              </div>
            </div>
          </el-form-item>
          <el-form-item label="门店地址">
            <el-input v-model="shopForm.station_address"></el-input>
          </el-form-item>
          <el-form-item label="门店经度">
            <el-input v-model="shopForm.lng"></el-input>
          </el-form-item>
          <el-form-item label="门店纬度">
            <el-input v-model="shopForm.lat"></el-input>
          </el-form-item>
  <!--         <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button>取消</el-button>
          </el-form-item> -->
        </el-form>
      </div>

      <el-button v-if="active == 1" style="margin:12px 50%;" @click="next" :disabled= "shopForm.station_name != '' ? false:true ">下一步</el-button>
      <el-button v-if="active > 1" style="margin:12px 50%;" @click="next">完成</el-button>
    </div>

    <div v-if="mchInfo">
    <el-row>
      <el-col :offset="8" :span="8">
        <el-radio-group v-model="cate" size="small" @change="changeMoney()">
            <el-radio-button label="1">运费账户</el-radio-button>
            <el-radio-button label="2">红包账户</el-radio-button>
            <el-radio-button label="3">所有</el-radio-button>
          </el-radio-group>
      </el-col>
    </el-row>
      
      <el-row style="margin: 12px 0;">
        <el-col :span='4'>账户金额：</el-col>
         <el-col :span='16'>{{moneyBalance}}元
           <p style="color: red;" v-if="cate != 2 && moneyBalance <= 50">请尽快充值，以免影响正常发单。</p>
         </el-col>
          <el-col :span='4' v-if="cate != 2">
            <el-button type="primary" plain @click="rechargeBtn">充值</el-button>
            <el-button type="warning" plain> <a href="https://newopen.imdada.cn">资金详情</a></el-button>
          </el-col>
      </el-row>
      <el-collapse v-model="activeNames" style>
        <el-collapse-item title="商户信息" name="1">
          <el-form label-width="150px">
            <el-form-item label="商户编号">
              {{shopForm.source_id}}
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item title="门店信息" name="2">
          
          <el-form label-width="150px">
            <el-form-item label="门店名称">{{shopForm.station_name}}</el-form-item>
            <el-form-item label="门店编码">{{shopForm.origin_shop_id}}</el-form-item>
            <el-form-item label="门店地址">{{shopForm.station_address}}</el-form-item>
            <el-form-item label="所在城市">{{shopForm.city_name}}</el-form-item>
            <el-form-item label="联系人姓名">{{shopForm.contact_name}}</el-form-item>
            <el-form-item label="联系人电话">{{shopForm.phone}}</el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" plain style="margin:12px 50%;" @click="shopUpdate">修改门店信息</el-button>
    </div>



    <!-- 充值 -->
    <el-dialog title="充值" :visible.sync="rechargeVisible" width="30%">

      <el-form ref="form" :model="moneyForm" label-width="80px">
        <el-form-item label="充值金额">
          <el-input-number v-model="moneyForm.money" :step="1"></el-input-number>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="rechargeVisible = false">取 消</el-button>
        <el-button type="primary" @click="recharge">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 更新门店 -->
     <el-dialog title="修改门店信息" :visible.sync="shopVisible" width="650px">

      <el-form ref="form" :model="shopForm" label-width="100px" >
          <el-form-item label="门店名称">
            <el-input v-model="shopForm.station_name"></el-input>
          </el-form-item>
          <el-form-item label="门店编码">
            <el-input v-model="shopForm.origin_shop_id"></el-input>
          </el-form-item>
<!--           <el-form-item label="门店编码">
            <el-input v-model="shopForm.new_shop_id"></el-input>
          </el-form-item> -->
          <el-form-item label="所在城市">
              <el-select v-model="shopForm.city_name" clearable placeholder="请选择城市">
                <el-option v-for="(item,index) in cityCode" :key="index" :label="item.cityName" :value="item.cityName"></el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="区域名称">
            <el-input v-model="shopForm.area_name"></el-input>
          </el-form-item>
          <el-form-item label="联系人姓名">
            <el-input v-model="shopForm.contact_name"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话">
            <el-input v-model="shopForm.phone"></el-input>
          </el-form-item>

          <el-form-item label="门店地址选取">
           <div class="amap-page-container">
              <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
              <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo"  :plugin="plugin"  :events="events">
                <el-amap-marker vid="amapDemo" :position="center" icon="https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" ></el-amap-marker>
                <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker" :events="clickMarker"></el-amap-marker>    
              </el-amap>
            </div>
          </el-form-item>
          <el-form-item label="门店地址">
            <el-input v-model="shopForm.station_address"></el-input>
          </el-form-item>
          <el-form-item label="门店经度">
            <el-input v-model="shopForm.lng"></el-input>
          </el-form-item>
          <el-form-item label="门店纬度">
            <el-input v-model="shopForm.lat"></el-input>
          </el-form-item>
        </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="shopVisible = false">取 消</el-button>
        <el-button type="primary" @click="shopUp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  
</template>

<script>
  export default {
    inject : ['reload'],
    data() {
      let self = this;
      return {
        shopInfo:[],
        cate:'3',
        mchInfo:[],
        mchCate:true,
        cityCode:[],
        moneyBalance:'',
        shopVisible:false,
// {"deliverBalance":10,"redPacketBalance":0}
        // form: {
        //   name: '',
        //   region: '',
        //   date1: '',
        //   date2: '',
        //   delivery: false,
        //   type: [],
        //   resource: '',
        //   desc: ''
        // },
        form:{
          source_id:'',
          city_code:''
        },
        mchForm:{
          mobile:'',
          city:'',
          city_name:'',
          city_code:'',
          enterprise_name:'',
          enterprise_address:'',
          contact_name:'',
          contact_phone:'',
          email:'',

        },
        moneyForm:{
          money:0,
        },
        activeNames: ['1','2'],
        rechargeVisible:false,
        business:[{"id":1,"type":"食品小吃"},{"id":2,"type":"饮料"},{"id":3,"type":"鲜花"},{"id":8,"type":"文印票务"},{"id":9,"type":"便利店"},{"id":13,"type":"水果生鲜"},{"id":19,"type":"同城电商"}, {"id":20,"type":"医药"},{"id":21,"type":"蛋糕"},{"id":24,"type":"酒品"},{"id":25,"type":"小商品市场"},{"id":26,"type":"服装"},{"id":27,"type":"汽修零配"},{"id":28,"type":"数码"},{"id":29,"type":"小龙虾"}, {"id":5,"type":"其他"}],
        shopForm:{
          station_name:'',
          business:'',
          city_name:'',
          area_name:'',
          station_address:'',
          lng:'',
          lat:'',
          contact_name:'',
          phone:'',
          origin_shop_id:'',
          source_id:'',
        },
        markers: [],
        searchOption: {city: '广州',citylimit: true},
            // mapCenter: [113.260782,23.119976],
        zoom: 12,
            // center: [121.59996, 31.197646],
        center: [113.260782,23.119976],
            // center: [self.admininfo.shopLon,self.admininfo.shopLat],
        address: '',
        events: {
          init(o){
            self.map = o;
          },
          click(e) {
            // self.markers = [];
            let { lng, lat } = e.lnglat;
            self.shopForm.lng = lng;
            self.shopForm.lat = lat;
            self.center = [e.lnglat.lng, e.lnglat.lat];//点击选择新地址为中心点

            // 这里通过高德 SDK 完成。
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });        
            geocoder.getAddress([lng ,lat], function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                  self.shopForm.station_address = result.regeocode.formattedAddress;
                  self.$nextTick();
                }
              }
            });        
          },
        },
         plugin: [],
        clickMarker:{
          click(e){
            let { lng, lat } = e.target.Uh.position;
            self.shopForm.lng = lng;
            self.shopForm.lat = lat;
            // console.log(e)
            // console.log(lng)
            // console.log(self.markers)
            self.center = [e.target.Uh.position.lng, e.target.Uh.position.lat];


            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            }); 


            geocoder.getAddress([lng, lat], function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                  self.shopForm.station_address = result.regeocode.formattedAddress;
                  self.$nextTick();
                }
              }
            });

          },

        },
        lng: 0,
        lat: 0,
        active: 0
      };
    },
    created(){
      this.init();
      // this.balance();
    },
    methods: {
      init(){
        // 获取商户
         this.$axios.get("admin/ddpeisong/mchinfo")
         .then((res) => {
            this.mchInfo = res.data.data
            // console.log(this.mchInfo.length)
            if(this.mchInfo == false){
              if(this.mchInfo.length > 0){
                this.active = 1
                this.mchCate = false
              }
            }
            
         })
        this.$axios.get("admin/ddpeisong/citycode")
        .then((res) => {
          if(res.data.code == 0 && res.data.status == 'success'){
            this.cityCode = res.data.result
          }
            
            // console.log(res)
        })
        this.$axios.get("admin/ddpeisong/shopInfo")
        .then((res) => {
          if(res.data.data){
            // this.shopForm = res.data.data
            this.center = [res.data.data.lng, res.data.data.lat]
            this.shopForm.station_name  = res.data.data.stationName
            this.shopForm.origin_shop_id = res.data.data.originShopId
            this.shopForm.city_name = res.data.data.cityName
            this.shopForm.area_name = res.data.data.areaName
            this.shopForm.contact_name = res.data.data.contactName
            this.shopForm.station_address = res.data.data.stationAddress
            this.shopForm.source_id = res.data.data.source_id
            this.shopForm.phone = res.data.data.phone
            this.shopForm.lng = res.data.data.lng
            this.shopForm.lat = res.data.data.lat
            this.shopForm.shop_id = res.data.data.dada_shop_id
            this.balance();
          }
        })
      },
      balance(){
        // 获取商户金额     76248
        // console.log(this.cate)
        this.$axios.get("admin/ddpeisong/balancequery",{params:{cate:this.cate}})
        .then((res) =>{
           // console.log(res);
           // console.log(res.data.result.deliverBalance)

           if(res.data.result.deliverBalance && res.data.result.redPacketBalance){
              this.moneyBalance = res.data.result.deliverBalance + res.data.result.redPacketBalance
           }else if('deliverBalance' in res.data.result){
              this.moneyBalance = res.data.result.deliverBalance
           }else{
              this.moneyBalance = res.data.result.redPacketBalance
           }
           
        })
      },
      next() {
        // if (this.active++ > 1){
        //   this.active = 0;  
        // }

        // this.mchCate = false
        if(this.active++ > 1){
          // 判断是否有商户数据和门店数据是否不为空
          if(this.mchInfo != false && this.shopForm != false){
            this.reload();
          }
        }else if(this.active == 1 && this.mchCate == true){

          this.mchForm.city_code = this.cityCode[this.mchForm.city].cityCode
          this.mchForm.city_name = this.cityCode[this.mchForm.city].cityName
          // console.log(this.cityCode)
          /* 注册 */
          this.$axios.post("admin/ddpeisong/merchant",this.mchForm)
          .then((res) => {
            if(res.data.code == 0 && res.data.status == 'success'){
              this.$message.success(res.data.msg)
            }else{
              this.$message.error(res.data.msg)
            }
          })
        }else if(this.active == 1 && this.mchCate == false){
          /* 填写 */
           this.$axios.post("admin/ddpeisong/addmch",this.form)
           .then((res) => {
            if(res.data.status == 0){
              this.$message.success(res.data.msg)
            }else{
              this.$message.error(res.data.msg)
            }
          })
        }else if(this.active == 2){
          /*创建门店*/
          this.$axios.post("admin/ddpeisong/shopAdd",this.shopForm)
          .then((res) => {
            if(res.data.code == 0 && res.data.status == 'success'){
              this.$message.success(res.data.msg)
            }else{
              this.$message.error(res.data.msg)
            }
          })
        }
      },
      addMarker: function() {
        let lng = 113.260782 + Math.round(Math.random() * 1000) / 10000;
        let lat = 23.119976 + Math.round(Math.random() * 500) / 10000;
        this.markers.push([lng, lat]);
        console.log(this.markers)
      },
      onSearchResult(pois) {
        let latSum = 0;
        let lngSum = 0;
        if (pois.length > 0) {
          pois.forEach(poi => {
            let {lng, lat} = poi;
            lngSum += lng;
            latSum += lat;
            this.markers.push([poi.lng, poi.lat]);
          });
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          };
          this.center = [center.lng, center.lat];
          // this.lng = center.lng
          // this.lat = center.lat
        }
      },
      hasMch(){
        this.mchCate = false
      },
      noMch(){
        this.mchCate = true
      },
      changeMoney(){
        // console.log(this.cate);
        if(this.cate == 1){
           this.balance();
        }else if(this.cate == 2){
           this.balance();
        }else{
           this.balance();
        }
      },
      rechargeBtn(){
        this.rechargeVisible = true
      },
      recharge(){
        this.$axios.get("admin/ddpeisong/recharge",{params:{money:this.moneyForm.money}})
        .then((res) => {
          // console.log(res.data.result)
          if(res.data.code == 0 && res.data.status == 'success'){
            window.location.href =res.data.result
          }else{
            this.$message.error(res.data.msg)
          }
        })
      },
      shopUpdate(){
        
        // if(this.shopForm.origin_shop_id != ''){
        //   this.location="https://newopen.imdada.cn"
        // }else{
          this.shopVisible = true
        // }
      },
      shopUp(){
        // console.log(this.shopForm)
        if(this.shopForm.source_id == ''){
          this.$axios.post("admin/ddpeisong/shopAdd",this.shopForm)
           .then((res) => {
            if(res.data.code == 0 && res.data.status == 'success'){
              this.$message.success(res.data.msg)
            }else{
              this.$message.error(res.data.msg)
            }
          })
        }else{
          this.$axios.post("admin/ddpeisong/shopupdate",this.shopForm)
            .then((res) => {
              if(res.data.code == 0 && res.data.status == 'success'){
                this.$message.success(res.data.msg)
              }else{
                this.$message.error(res.data.msg)
              }
            })

        }
        this.shopVisible = false
        
      }
      // handleClose(done) {
      //   this.$confirm('确认关闭？')
      // }
    }
  }
</script>
<style type="text/css">
   /*地图*/
    .amap-demo {
      height: 300px;
    }

    .search-box {
      position: absolute;
      top: 50px;
      left: 20px;
    }
    .toolbar{
      margin-top: 15px;
    }
    .amap-page-container {
      position: relative;
    }
    .el-vue-amap{
      height: 300px !important;
      width: 600px !important;
      left:-100px;
    }
</style>